package com.dream.xiaobo.dao.impl;

import com.dream.xiaobo.dao.TypeDao;
import com.dream.xiaobo.entity.Type;
import com.dream.xiaobo.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author xiaobo
 * @date 2021/8/31 - 10:33
 */
public class TypeDaoImpl implements TypeDao {

    //创建QueryRunner实例化对象
    private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    /**
     * 查询商品分类
     * @return
     * @throws SQLException
     */
    @Override
    public List<Type> selectAll() throws SQLException {

        //查询商品分类的全部信息的SQL
        String sql = "SELECT t_id AS tId,t_name AS tName,t_info AS tInfo FROM type";

//        String sql = "SELECT t_id AS tId,t_name AS tName,t_info AS tInfo FROM type LIMIT 5";
        //执行SQL
        List<Type> list = queryRunner.query(sql, new BeanListHandler<Type>(Type.class));

        //返回结果
        return list;
    }

    /**
     * 根据商品类别Id查询信息的方法
     * @param tId
     * @return
     * @throws SQLException
     */
    @Override
    public Type selectByTid(String tId) throws SQLException {

        //根据商品类别Id查询信息的SQL
        String sql = "SELECT t_id AS tId, t_name AS tName, t_info AS tInfo FROM type WHERE t_id = ?";
        //执行SQL
        Type type = queryRunner.query(sql, new BeanHandler<Type>(Type.class), tId);
        //返回查询到的结果
        return type;
    }

    @Override
    public void insertType(Type type) throws SQLException {
        String sql = "INSERT INTO type(t_name,t_info) VALUES(?,?)";

        queryRunner.update(sql,type.gettName(),type.gettInfo());

    }

}
